package com.common.sub.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.casicloud.manage.model.User;
import com.casicloud.manage.model.UserRole;
import com.casicloud.manage.service.UserRoleService;
import com.casicloud.manage.service.UserService;
import com.common.sub.util.ControllerBase;

@Controller
public class IndexController extends ControllerBase{

	@Autowired
	private UserService userService;
	
	@Autowired
	private UserRoleService userRoleService;
	
	
	private static final Log logger = LogFactory.getLog(IndexController.class);

	@RequestMapping(value = "404")
	public String e404(HttpServletRequest request,HttpServletResponse response) {
		
		return "404";
	}
	@RequestMapping(value = "500")
	public String e500(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "500";
	}
	@RequestMapping(value = "400")
	public String e400(HttpServletRequest request,HttpServletResponse response) throws IOException{
		return "400";
	}
	

	
	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(HttpServletRequest request,HttpServletResponse response){
		return "index";
	}
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String gologin(HttpServletRequest request,HttpServletResponse response){
		return "login";
	}
	
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String dologin(User user,HttpServletRequest request,HttpServletResponse response){
		if(user!=null){
			UsernamePasswordToken token =new UsernamePasswordToken(user.getUsername(),user.getPassword());
			try {
				SecurityUtils.getSubject().login(token);
				
				return "redirect:index.html";
			} catch (Exception e) {
				logger.error("login fail",e);
			}
		}
		return "redirect:login.html";
	}
	
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request,HttpServletResponse response) throws IOException{
		SecurityUtils.getSubject().logout();
		this.deleteSessionUser();
		return "redirect:login.html";
	}

}
